
package webshop.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import webshop.data.Product;



/**
 * Servlet that finds a spesific product in the database.
 * @author Ohm & simon.
 */
public class ProductFindServlet extends AbstractSuperServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        EntityManager em = emf.createEntityManager();
        PrintWriter out = response.getWriter();

        // Parameters.
        String productName = request.getParameter("productname");
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>"+this.getClass().getName()+"</title></head><body>");
        out.println("<h1>Product Finder</h1>");

        out.println("<table>");
        out.println("<tr><th>Product</th></tr>");

        // Get database content.
        Query q = em.createNamedQuery("Product.selectAll");
        List<Product> products = q.getResultList();
        // Search for product and print if found.
        for (Product product : products) {
            if ((product.getName().toLowerCase()).equals(productName.toLowerCase()))
                out.println("<tr><td>"+product.getProductId()+"</td><td>"+
                         product.getName()+"</td><td>"+
                         product.getDescription()+"</td><td>"+
                         product.getPrice()+"</td><td>"+
                         product.getStock()+"</td></tr>");



        }

 


        out.println("</table>");

        out.println("<hr/>");
        out.println("<p><a href=\"index.html\">Home</a></p>");

        out.println("</body>");
        out.println("</html>");

        em.close();
        }
}